#-*- coding:utf-8 -*-
from models import ND

from flask import Flask, render_template
from flask import jsonify
from flask import request, session, redirect, url_for
import urllib, urllib2, json
import glob
import os
app = Flask(__name__)
app.secret_key = 'adf$@*B@*S)Nz0ab092bs'
DEBUG = os.getenv('NUIDEBUG')

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'GET':
        data = []
        if session.has_key('login'):
            src = "*.log" if DEBUG else "/data/logs/access/*.log"   #TODO: using Config
            data = []
            for file in glob.glob(src):
                data.append(file)
            return render_template('index.html', data=data)
        return render_template('login.html')
    elif request.method == 'POST':
        data = request.form
        if data.get('password') == 'icaib':
            session['login'] = 1
        return redirect(url_for('index'))

@app.route('/file')
def file():
    if not session.has_key('login'):
        return redirect(url_for('index'))
    file = request.args.get('file')
    if file:
        return render_template('chart.html', file=file)
    else:
        return jsonify(msg='No file Input')

@app.route('/chart')
def chart():
    if not session.has_key('login'):
        return jsonify(msg='Auth failed')

    file = request.args.get('file')
    if not file.endswith('log'):
        return jsonify(msg='"*.log" log file only')

    obj = ND(file)
    (ip, time, target, status, referer, ghost ) = obj.query()
    data = {
        'ip': ip,
        'req_time': time,
        'status': status,
        'target': target,
        'referer': referer,
        'ghost': ghost
    }
    return jsonify(data)

@app.route('/ip/<ip>')
def ip_info(ip):
    if ip is not None:
        url = 'http://ip.taobao.com/service/getIpInfo.php?ip=%s' % ip
    req = urllib2.Request(url) # exception?
    response = urllib2.urlopen(req)
    data = json.loads(response.read())
    if data.has_key('code') and data['code'] == 0 :
        d = data['data']
        res = u'{0} {1} {2} {3}'.format(d['country'], d['region'], d['city'], d['isp'])
        return res
    return 'shit'


if __name__ == '__main__':
    app.run(debug=True)